/*
 * CS_REQ_EXTEND_PERIOD.cpp
 *
 *  Created on: 2014. 1. 15.
 *      Author: the2
 */


#include "../../Command.h"
#include "../../User.h"
#include "../../NResource/Static.h"
#include "../../NLogic/Item.h"
#include "../../NLogic/Bag.h"
#include "../../NLogic/VirtualCurrency.h"

namespace ProjectZ { namespace NCommand {

static void SendAckFail(User * pUser, int res)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();

	*pAck << static_cast<int16_t>(res);

	pAck->MakePacket(CMD_SC_REQ_EXTEND_PERIOD);

	pUser->Send(pAck);
}

void Command::CS_REQ_EXTEND_PERIOD(User * pUser, ::Network::Packet * pPacket) {

	PREPARE_PACKET;

	uint64_t	itemSeq = 0;
	uint8_t		bagType = 0;
	uint16_t	vcIdx = 0;
	uint32_t	zen = 0;

	*pPacket >> itemSeq >> bagType >> vcIdx >> zen;

	DEBUGLOG("CS_BUY_ITEM_WITH_ZEN : user_seq=%d, charge_seq=%d", pUser->GetUserSeq(), itemSeq);

	// 유저의 보유ZEN 확인
	if ((pUser->GetVirtualCurrency()->GetZen() - zen) < 0)
	{
		DEBUGLOG("CS_BUY_ITEM_WITH_ZEN : Not Enought ZEN!!");
		SendAckFail(pUser, ACK_NOT_ENOUGH_ZEN);
		return;
	}

	NLogic::Bag * pBag = pUser->GetBag(static_cast<INVEN_BAG_TYPE>(bagType));
	if (NULL == pBag)
	{
		DEBUGLOG("CS_BUY_ITEM_WITH_ZEN : pBag is NULL!!! bagtype=%d", bagType);
		SendAckFail(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	NLogic::Item * pItem = pBag->GetItem(itemSeq);

	if (NULL == pItem)
	{
		DEBUGLOG("CS_BUY_ITEM_WITH_ZEN : pItem is NULL!!!");
		SendAckFail(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	pItem->GetData().reg_date = time(NULL);

	if (false == pItem->UpdateDatabaseItemInfo())
	{
		DEBUGLOG("CS_BUY_ITEM_WITH_ZEN : pItem update error!!!");
		SendAckFail(pUser, ACK_DB_ERROR);
		return;
	}

	// VC 처리
	NLogic::NFunction::VCProcess(pUser, vcIdx);

	// 응답
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ACK_OK);
	pAck->MakePacket(CMD_SC_REQ_EXTEND_PERIOD);
	pUser->Send(pAck);

	NLogic::NFunction::SendInvenItemUpdate(pUser, pItem);
}

} /*NCommand*/ } /*ProjectZ*/

